<template>
    <div>
        <div class="base-title">基本信息</div>
        <el-form
            ref="queryForm"
            :model="queryForm"
            :rules="rules"
            label-width="90px"
            size="mini"
            class="bg-white"
            label-position="right"
        >
            <el-row :gutter="10">
                <el-col :span="6">
                    <el-form-item label="模板名称：" prop="templateName">
                        <el-input
                            v-if="!isRead"
                            v-model="queryForm.templateName"
                            style="width:100%"
                            type="text"
                            placeholder="请输入模板名称"
                            size="mini"
                        />
                        <span v-if="isRead">{{ queryForm.templateName }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="年级：" prop="year">
                        <el-date-picker
                                v-model="queryForm.year"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择学年"
                                style="width: 100%"
                            />
                        <span v-if="isRead">{{ queryForm.year }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="培养层次：" prop="trainingLevel">
                        <el-select
                            v-if="!isRead"
                            v-model="queryForm.trainingLevel"
                            style="width:100%"
                            size="mini"
                        >
                            <el-option
                                v-for="item in options.trainingLevel"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                        <span
                            v-if="isRead"
                        >{{ getTrainingLevelLabelByValue(queryForm.trainingLevel) }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="培养类别：" prop="trainingCategory">
                        <el-select
                            v-if="!isRead"
                            v-model="queryForm.trainingCategory"
                            style="width:100%"
                            size="mini"
                            placeholder="全部"
                            clearable multiple collapse-tags
                        >
                            <el-option
                                v-for="item in options.trainingCategory"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                            />
                        </el-select>
                        <span
                            v-if="isRead"
                        >{{ getformLearningLabelByValue(queryForm.trainingCategory) }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="学习形式：" prop="formLearning">
                        <el-select
                            v-if="!isRead"
                            v-model="queryForm.formLearning"
                            style="width:100%"
                            size="mini"
                            placeholder="全部"
                            clearable
                        >
                            <el-option
                                v-for="item in options.formLearning"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                        <span
                            v-if="isRead"
                        >{{ getformLearningLabelByValue(queryForm.formLearning) }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$t('culture.scheme.degreeType') + '：'" prop="degreeType">
                        <el-select
                            v-if="!isRead"
                            v-model="queryForm.degreeType"
                            style="width:100%"
                            size="mini"
                            clearable
                            placeholder="全部"
                        >
                            <el-option
                                v-for="item in options.degreeType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                        <span
                            v-if="isRead"
                        >{{ getformLearningLabelByValue(queryForm.trainingCategory) }}</span>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div class="base-title">章节划分</div>
        <el-table :data="chapters" size="mini">
            <el-table-column prop="id" label="序号" width="100"/>
            <el-table-column label="章节名称">
                <template slot-scope="props">
                    <el-input
                        v-if="props.row.id==selectChapterId||props.row.opr=='new'"
                        v-model="props.row.name"
                        type="text"
                    />
                    <span
                        v-if="props.row.id!=selectChapterId&&props.row.opr=='normal'"
                    >{{ props.row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column label="英文名称">
                <template slot-scope="props">
                    <el-input
                        v-if="props.row.id==selectChapterId||props.row.opr=='new'"
                        v-model="props.row.nameEn"
                        type="text"
                    />
                    <span
                        v-if="props.row.id!=selectChapterId&&props.row.opr=='normal'"
                    >{{ props.row.nameEn }}</span>
                </template>
            </el-table-column>
            <el-table-column label="内容导入方式">
                <template slot-scope="props">
                    <el-select
                        v-if="props.row.id==selectChapterId||props.row.opr=='new'"
                        v-model="props.row.contentType"
                        style="width:100%"
                    >
                        <el-option label="直接输入" value="1"/>
                        <el-option label="系统表格" value="2"/>
                    </el-select>
                    <span
                        v-if="props.row.id!=selectChapterId&&props.row.opr=='normal' && props.row.contentType == 1"
                    >直接输入</span>
                    <span
                        v-if="props.row.id!=selectChapterId&&props.row.opr=='normal' && props.row.contentType == 2"
                    >系统表格</span>
                </template>
            </el-table-column>
            <el-table-column label="排序序号" width="100">
                <template slot-scope="props">
                    <el-input
                        v-if="props.row.id==selectChapterId||props.row.opr=='new'"
                        v-model="props.row.sortNo"
                        type="text"
                    />
                    <span
                        v-if="props.row.id!=selectChapterId&&props.row.opr=='normal'"
                    >{{ props.row.sortNo }}</span>
                </template>
            </el-table-column>
            <el-table-column v-if="!isRead" label="操作">
                <template slot-scope="props">
                    <el-button
                        v-if="props.row.opr=='normal'&&props.row.id!=selectChapterId"
                        type="text"
                        size="mini"
                        @click="editRow(props.row)"
                    >编辑</el-button>
                    <el-button
                        v-if="props.row.opr=='normal'&&props.row.id!=selectChapterId"
                        type="text"
                        size="mini"
                        @click="removeRow(props.row)"
                    >删除</el-button>
                    <el-button
                        v-if="props.row.opr=='normal'&&props.row.id==selectChapterId"
                        type="text"
                        size="mini"
                        @click="cancelRow(props.row)"
                    >取消</el-button>
                    <el-button
                        v-if="props.row.opr=='new'"
                        type="text"
                        size="mini"
                        @click="addRow(props.row)"
                    >新增</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row class="pd-12px float-right">
            <el-col :span="24">
                <el-button size="medium" @click="back">返回</el-button>
                <el-button v-if="!isRead" size="medium" @click="submit">保存</el-button>
                <el-button size="medium" type="primary" @click="nextStep">下一步</el-button>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import Constant from "common/src/utils/constant";
import { queryDic, findTrainingLevelByProjId, sortTrainingCategories } from "common/src/api/dictionary";
import {
    saveCultureTemplate,
    getCultureTemplateById
} from "common/src/api/courseTemplate";
import Bus from "common/src/utils/bus";
import UTILS from "common/src/utils/utils";
import { mapActions } from "vuex";
const ROW_TYPE = {
    NORMAL: "normal",
    NEW: "new"
};
export default {
    name: "template-base-info",
    props: {
        next: {
            type: Function,
            default: null
        },
        templateId: {
            type: String,
            default: null
        },
        isRead: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            queryForm: {
                "x-token": "",
                templateName: "",
                year: "",
                trainingLevel: "",
                formLearning: "",
                trainingCategory: [],
                degreeType: "",
                font: "",
                fontSize: 14
            },
            options: {
                year: [],
                trainingLevel: [],
                formLearning: [],
                trainingCategory: [],
                degreeType: []
            },
            chapters: [],
            selectChapterId: 0,
            currentDeleteId: 0,
            rules: {
                templateName: [
                    {
                        required: true,
                        message: "请填写模板名称",
                        trigger: "blur"
                    }
                ],
                year: [
                    {
                        required: true,
                        message: "请选择年级",
                        trigger: "blur"
                    }
                ],
                trainingLevel: [
                    {
                        required: true,
                        message: "请选择培养层次",
                        trigger: "blur"
                    }
                ],
                formLearning: [
                    {
                        required: false,
                        message: "请选择学习形式",
                        trigger: "blur"
                    }
                ],
                trainingCategory: [
                    {
                        required: true,
                        message: "请选择培养类别",
                        trigger: "blur"
                    }
                ],
                degreeType: [
                    {
                        required: false,
                        message: "请选择学位类型",
                        trigger: "blur"
                    }
                ]
            }
        };
    },
    mounted() {
        this.init();
    },
    created() {},
    methods: {
        ...mapActions(["delTab"]),
        init() {
            let params = {
                lang: this.$store.getters.language,
                keys: ["X_PYLB"]
            };
            sortTrainingCategories(params).then((res) => {
                this.options.trainingCategory = res.data.X_PYLB;
            });

            this.queryForm["x-token"] =
                this.$store.state.session.sessionid ||
                localStorage.getItem("sessionid") ||
                "";
            // 绑定年级
            const now = new Date();
            const currentYear = now.getFullYear()+1;
            const minYear = currentYear - 6;
            for (let year = currentYear; year > minYear; year--) {
                const obj = { label: year, value: year };
                this.options.year.push(obj);
            }
            // 绑定培养层次
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["K_XXXS", "X_PYLB", "X_XWLX"]
            };
            queryDic(data).then(res => {
                if (res.code === 200) {
                    UTILS.fillSelect(
                        {
                            formLearning: "K_XXXS",
                            // trainingCategory: "X_PYLB",
                            degreeType: "X_XWLX"
                        },
                        res.data,
                        this.options
                    );
                    
                    if (this.templateId) {
                        this.getTemplateInfo(this.templateId);
                    } else {
                        this.appendCreateRow();
                    }
                }
            });
            findTrainingLevelByProjId(this.$route.params.projId).then(res => {
                if (res.code === 200) {
                    this.loadTrainingLevelOptions("trainingLevel", res.data);
                }
            });
            // 使用默认
            this.queryForm.font = Constant.cultureTemplateChapter.font;
            this.queryForm.fontSize = Constant.cultureTemplateChapter.fontSize;
        },
        loadTrainingLevelOptions(optionKey, dataObj) {
            _.each(dataObj, level => {
                this.options[optionKey].push({
                    label:
                        "en" === this.$store.getters.language
                            ? level.nameEN
                            : level.nameCN,
                    value: level.code
                });
            });
        },
        // 获取模板信息
        getTemplateInfo(id) {
            getCultureTemplateById(id).then(response => {
                if (response.code === 200) {
                    this.queryForm.templateName = response.data.name;    
                    var year=String(response.data.year);
                   
                    this.queryForm.year =year;
                    this.queryForm.trainingLevel = response.data.trainingLevel;
                    this.queryForm.formLearning = response.data.formLearning;
                    this.queryForm.degreeType = response.data.degreeType;
                    this.queryForm.font = response.data.font;
                    this.queryForm.trainingCategory =
                        response.data.trainingCategory ? response.data.trainingCategory.split(",") : [];
                    this.queryForm.fontSize = response.data.fontSize;
                    const chapters = [];
                    if (response.data.sonCultureTemplateList.length > 0) {
                        response.data.sonCultureTemplateList.forEach(
                            (row, index) => {
                                chapters.push({
                                    id: index + 1,
                                    name: row.name,
                                    nameEn: row.nameEn,
                                    sortNo: row.sortNo,
                                    contentType: row.contentType
                                        ? row.contentType.toString()
                                        : "",
                                    opr: ROW_TYPE.NORMAL,
                                    font: row.font,
                                    fontSize: row.fontSize,
                                    realId: row.id
                                });
                            }
                        );
                    }
                    this.chapters = chapters;
                    this.appendCreateRow();
                }
            });
        },
        // 新增
        addRow(row) {
            if (row.name.trim() === "") {
                this.$message({
                    type: "info",
                    message: "请填写章节名称"
                });
                return;
            }
            row.opr = ROW_TYPE.NORMAL;
            this.appendCreateRow();
        },
        editRow(row) {
            this.selectChapterId = row.id;
        },
        removeRow(row) {
            this.$confirm("是否删除该章节?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    this.currentDeleteId = row.id;
                    this.confirmDelete();
                })
                .catch(e => {});
        },
        cancelRow(row) {
            this.selectChapterId = 0;
        },
        // 添加新增行
        appendCreateRow() {
            if (!this.isRead) {
                const row = {
                    id: "",
                    name: "",
                    nameEn: "",
                    sortNo: "",
                    contentType: "1",
                    fontSize: this.queryForm.fontSize,
                    font: this.queryForm.font,
                    opr: ROW_TYPE.NEW
                };
                if (this.chapters.length === 0) {
                    row.id = 1;
                    row.sortNo = 1;
                } else {
                    const maxObject = _.maxBy(this.chapters, c => c.id);
                    row.id = parseInt(maxObject.id) + 1;
                    row.sortNo = row.id;
                }
                this.chapters.push(row);
            }
        },
        // 删除当前行，重新设置序号,排除新增行
        confirmDelete() {
            const newChapters = _.cloneDeep(this.chapters);
            _.remove(newChapters, c => c.id === this.currentDeleteId);
            newChapters.forEach((c, index) => {
                if (c.id) {
                    c.id = parseInt(index) + 1;
                }
                if (c.opr === ROW_TYPE.NEW) {
                    c.sortNo = c.id;
                }
            });

            this.chapters = newChapters;
        },
        // 返回
        back() {
            Bus.$emit("selectCultureTemplate");
            this.delTab("/cultureTemplateDetail");
            window.history.back();
        },
        isValid() {
            let result = true;
            let msg = "";
            const reg = new RegExp(/^\d+$/);
            this.chapters.forEach(c => {
                if (
                    result &&
                    (c.opr === ROW_TYPE.NORMAL ||
                        (c.opr === ROW_TYPE.NEW && c.name.trim() !== ""))
                ) {
                    if (c.name.trim() === "") {
                        result = false;
                        msg = "章节名称不能为空";
                    } else if (c.nameEn.trim() === "") {
                        result = false;
                        msg = "章节英文名称不能为空";
                    } else if (
                        c.sortNo == null ||
                        c.sortNo.toString().trim() === "" ||
                        !reg.test(c.sortNo.toString().trim())
                    ) {
                        result = false;
                        msg = "章节排序序号必须是数字";
                    }
                }
            });
            if (!result) {
                this.$message({
                    type: "info",
                    message: msg
                });
            }
            return result;
        },
        // 保存
        submit() {
            this.$refs.queryForm.validate(valid => {
                if (!valid) {
                    return;
                }
                if (!this.isValid()) {
                    return;
                }
                // 移除空的新增行
                const chapters = this.chapters.filter(
                    c =>
                        c.opr === ROW_TYPE.NORMAL ||
                        (c.opr === ROW_TYPE.NEW && c.name.trim() !== "")
                );
                if (chapters.length === 0) {
                    // this.$confirm("未添加章节信息，是否继续保存?", "提示", {
                    //     confirmButtonText: "确定",
                    //     cancelButtonText: "取消",
                    //     type: "warning"
                    // }).then(() => {
                    //     this.postData();
                    // });
                    this.$message({
                        type: "warning",
                        message: "请添加章节信息"
                    });
                    return
                } else {
                    let containTable = false; // 导入方式是否包含表格
                    chapters.forEach(c => {
                        if (!containTable && c.contentType === "2") {
                            containTable = true;
                        }
                    });
                    if (!containTable) {
                        this.$confirm(
                            "章节中不包含系统表格，是否继续保存?",
                            "提示",
                            {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "warning"
                            }
                        ).then(() => {
                            this.postData();
                        });
                    } else {
                        this.postData();
                    }
                }
            });
        },
        postData() {
            // 处理提交数据
            const data = {
                projId: this.$route.params.projId,
                id: this.templateId,
                year: this.queryForm.year,
                name: this.queryForm.templateName.trim(),
                trainingLevel: this.queryForm.trainingLevel,
                formLearning: this.queryForm.formLearning,
                trainingCategory: this.queryForm.trainingCategory,
                degreeType: this.queryForm.degreeType,
                font: this.queryForm.font,
                fontSize: this.queryForm.fontSize,
                sonCultureTemplateList: []
            };
            this.chapters.forEach(c => {
                if (
                    c.opr === ROW_TYPE.NORMAL ||
                    (c.opr === ROW_TYPE.NEW && c.name.trim() !== "")
                ) {
                    const row = {
                        name: c.name.trim(),
                        nameEn: c.nameEn.trim(),
                        sortNo: c.sortNo.toString().trim(),
                        contentType: c.contentType,
                        font: c.font,
                        fontSize: c.fontSize
                    };
                    if (c.realId) {
                        row.id = c.realId;
                    }
                    data.sonCultureTemplateList.push(row);
                }
            });
            // 保存模板和章节信息
            saveCultureTemplate(data).then(response => {
                if (response.code === 200) {
                    Bus.$emit("saveTemplate", response.data);
                    this.$message({
                        type: "success",
                        message: "保存模板成功"
                    });
                    this.selectChapterId = 0;
                }
            });
        },
        // 下一步
        nextStep() {
            if (this.next) {
                this.next();
            }
        },
        getTrainingLevelLabelByValue(value) {
            const option = this.options.trainingLevel.find(
                t => t.value === value
            );
            if (option) {
                return option.label;
            } else {
                return "";
            }
        },
        getformLearningLabelByValue(value) {
            const option = this.options.formLearning.find(
                f => f.value === value
            );
            if (option) {
                return option.label;
            } else {
                return "";
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.base-title {
    border-bottom: 1px solid #cccccc;
    line-height: 30px;
    margin-bottom: 20px;
}
</style>
